package com.hotel.BL;

import java.util.ArrayList;
import java.util.List;

import com.EntityName;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import data.Group;

public class GroupLogic extends AbstractBL {
	public Group GetGroupById(long id) {
		Key key = KeyFactory.createKey(EntityName.Group, id);
		try {
			Entity e = datastore.get(key);
			Group g = new Group();
			g.setEntity(e);
			
			return g;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	public Group UpdateGroup(Group group) throws EntityNotFoundException
	{
		Key key = datastore.put(group.getEntity());
		group.setId(key.getId());
		group.setKey(key);
		return group;
	}
	public long GetMaxGroupDisplayId(long hotelId)
	{
		Query q = new Query(EntityName.Group);

		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("displayId", SortDirection.DESCENDING);
		try{
			List<Group> list = GetGroupList(datastore.prepare(q).asList(
					FetchOptions.Builder.withLimit(1)));
			if(list.size()>0)
				return list.get(0).getDisplayId();
			return 0;
		}catch(Exception ex){return 0;}
	}
	public List<Group> GetGroupList(List<Entity> entities) {
		List<Group> list = new ArrayList<Group>();
		if(entities!=null)
		for (Entity e : entities) {
			Group a = new Group();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}
}
